package com.funo.logic.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.funo.logic.model.QueryConfig;
import com.funo.logic.response.HandleResult;
import com.funo.logic.service.CompilationInParameterService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("queryConfig")
public class QueryConfigController extends AbstractController{

    private static final String NODE_NAME = "查询单条";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CompilationInParameterService compilationInParameterService;

    /**
     * 保存或更新查询配置
     * @param queryConfig
     * @return HandleResult
     * @since 2024年7月18日14:53:44
     */
    @PostMapping("saveOrUpdate")
    public HandleResult saveOrUpdate(@RequestBody QueryConfig queryConfig) {
        String belongNodeId = queryConfig.getBelongNodeId();
        String cacheKey = getCacheKey(belongNodeId);
        stringRedisTemplate.delete(cacheKey);
        if (CollectionUtil.isNotEmpty(queryConfig.getQueryParameterList())) {
            queryConfig.getQueryParameterList().stream().forEach(queryParameter -> {
                String[] nameCode = queryParameter.getQueryParam().split("/");
                queryParameter.setName(nameCode[0]);
                queryParameter.setCode(nameCode[1]);
                queryParameter.setBelongNodeId(belongNodeId);
            });
        }
        if (queryConfig.getQueryResponse() != null) {
            queryConfig.getQueryResponse().setBelongNodeId(belongNodeId);
            queryConfig.getQueryResponse().setNodeName(NODE_NAME);
            compilationInParameterService.addOrUpdateQueryResponse(queryConfig.getArrangeId(), queryConfig.getQueryResponse());
        }
        stringRedisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(queryConfig));
        return HandleResult.success();
    }

    /**
     * 根据所属id查询
     * @param belongNodeId 所属模块id
     * @return HandleResult
     */
    @GetMapping("getByBelongNodeId")
    public HandleResult getByBelongNodeId(String belongNodeId) {
        String cacheKey = getCacheKey(belongNodeId);
        String value = stringRedisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isBlank(value)) {
            return HandleResult.success();
        }
        return HandleResult.success(JSONUtil.toBean(value, QueryConfig.class));
    }

    public String getCachePrefix() {
        return "queryConfig:";
    }
}
